<template>
  <div class="kefu-websocket">
    <div class="header">
      <h2>客服聊天系统</h2>
      <div class="connection-status">
        <span :class="['status-indicator', isConnected ? 'connected' : 'disconnected']"></span>
        <span>{{ isConnected ? '已连接' : '未连接' }}</span>
        <button @click="toggleConnection" :disabled="connecting">
          {{ connecting ? '连接中...' : isConnected ? '断开' : '连接' }}
        </button>
      </div>
    </div>

    <div v-if="isConnected" class="chat-container">
      <div class="user-input">
        <input
            v-model="targetUserId"
            placeholder="目标用户ID（私聊）"
        />
        <input
            v-model="message"
            placeholder="输入消息"
            @keyup.enter="handleSend"
        />
        <button @click="handleSend" :disabled="!message.trim()">发送</button>
        <button @click="handleBroadcast" :disabled="!message.trim()">广播</button>
      </div>

      <div class="messages">
        <div
            v-for="(msg, index) in messageList"
            :key="index"
            :class="['message', msg.type]"
        >
          <div class="message-content">
            <span class="timestamp">{{ formatTime(msg.timestamp) }}</span>
            <span class="content">{{ msg.content }}</span>
          </div>
        </div>
      </div>
    </div>

    <div v-else class="connection-form">
      <div>
        <input
            v-model="userId"
            placeholder="请输入用户ID"
            @keyup.enter="handleConnect"
        />
        <button @click="handleConnect" :disabled="!userId.trim() || connecting">
          {{ connecting ? '连接中...' : '连接' }}
        </button>
      </div>
    </div>
  </div>
</template>

<script>
import { ref, onMounted, onUnmounted } from 'vue';
import webSocketService from '@/websocket/service';

export default {
  setup() {
    // 响应式数据
    const userId = ref('');
    const targetUserId = ref('');
    const message = ref('');
    const connecting = ref(false);
    const isConnected = ref(false);
    const messageList = ref([]);

    // 处理连接/断开
    const toggleConnection = () => {
      if (isConnected.value) {
        disconnect();
      } else {
        handleConnect();
      }
    };

    // 处理连接
    const handleConnect = async () => {
      if (!userId.value.trim()) {
        alert('请输入用户ID');
        return;
      }

      connecting.value = true;
      try {
        // 注册事件回调
        setupEventListeners();

        // 连接WebSocket
        const result = await webSocketService.connect(userId.value);
        isConnected.value = result;

        if (!result) {
          alert('连接失败');
          removeEventListeners();
        }
      } catch (error) {
        alert('连接时发生错误');
        removeEventListeners();
      } finally {
        connecting.value = false;
      }
    };

    // 处理发送消息
    const handleSend = () => {
      if (!message.value.trim()) return;

      if (targetUserId.value.trim()) {
        // 发送私聊消息
        webSocketService.sendPrivateMessage(targetUserId.value, message.value);
      } else {
        // 发送普通消息
        webSocketService.sendMessage(message.value);
      }

      // 添加到本地消息列表
      addLocalMessage('sent', message.value);
      message.value = '';
    };

    // 处理广播消息
    const handleBroadcast = () => {
      if (!message.value.trim()) return;

      webSocketService.sendBroadcastMessage(message.value);

      // 添加到本地消息列表
      addLocalMessage('sent', `广播: ${message.value}`);
      message.value = '';
    };

    // 断开连接
    const disconnect = () => {
      webSocketService.disconnect();
      isConnected.value = false;
      removeEventListeners();
    };

    // 添加本地消息
    const addLocalMessage = (type, content) => {
      messageList.value.push({
        type,
        content,
        timestamp: new Date()
      });
    };

    // 格式化时间
    const formatTime = (date) => {
      return date.toLocaleTimeString();
    };

    // 设置事件监听器
    const setupEventListeners = () => {
      webSocketService.on('connect', () => {
        isConnected.value = true;
        addLocalMessage('system', '连接成功');
      });

      webSocketService.on('disconnect', () => {
        isConnected.value = false;
        addLocalMessage('system', '连接已断开');
      });

      webSocketService.on('error', (error) => {
        addLocalMessage('error', `连接错误: ${error.message || '未知错误'}`);
      });

      webSocketService.on('message', (message) => {
        addLocalMessage('received', message);
      });
    };

    // 移除事件监听器
    const removeEventListeners = () => {
      webSocketService.off('connect');
      webSocketService.off('disconnect');
      webSocketService.off('error');
      webSocketService.off('message');
    };

    // 组件卸载时清理
    onUnmounted(() => {
      disconnect();
    });

    // 组件挂载时可以进行一些初始化
    onMounted(() => {
      console.log('WebSocket组件已挂载');
    });

    return {
      userId,
      targetUserId,
      message,
      connecting,
      isConnected,
      messageList,
      toggleConnection,
      handleConnect,
      handleSend,
      handleBroadcast,
      formatTime
    };
  }
};
</script>

<style scoped>
.kefu-websocket {
  max-width: 800px;
  margin: 0 auto;
  padding: 20px;
}

.header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
}

.connection-status {
  display: flex;
  align-items: center;
  gap: 10px;
}

.status-indicator {
  width: 12px;
  height: 12px;
  border-radius: 50%;
}

.status-indicator.connected {
  background-color: #4caf50;
}

.status-indicator.disconnected {
  background-color: #f44336;
}

.user-input {
  display: flex;
  gap: 10px;
  margin-bottom: 20px;
  flex-wrap: wrap;
}

.user-input input {
  flex: 1;
  min-width: 120px;
  padding: 8px;
  border: 1px solid #ddd;
  border-radius: 4px;
}

.user-input button {
  padding: 8px 16px;
  border: none;
  border-radius: 4px;
  background-color: #2196f3;
  color: white;
  cursor: pointer;
}

.user-input button:disabled {
  background-color: #ccc;
  cursor: not-allowed;
}

.messages {
  border: 1px solid #ddd;
  border-radius: 4px;
  height: 400px;
  overflow-y: auto;
  padding: 10px;
}

.message {
  margin-bottom: 10px;
  padding: 8px;
  border-radius: 4px;
}

.message.sent {
  background-color: #e3f2fd;
  text-align: right;
}

.message.received {
  background-color: #f5f5f5;
}

.message.system {
  background-color: #fff3e0;
  text-align: center;
  font-style: italic;
}

.message.error {
  background-color: #ffebee;
  color: #f44336;
}

.message-content {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.timestamp {
  font-size: 0.8em;
  color: #999;
  margin-right: 10px;
}

.content {
  flex: 1;
}

.connection-form {
  text-align: center;
  padding: 50px;
}

.connection-form input {
  padding: 10px;
  margin-right: 10px;
  border: 1px solid #ddd;
  border-radius: 4px;
}

.connection-form button {
  padding: 10px 20px;
  border: none;
  border-radius: 4px;
  background-color: #2196f3;
  color: white;
  cursor: pointer;
}
</style>